package model.data
{
	import flash.desktop.NativeApplication;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.Dictionary;

	public class Book extends BaseData
	{
		public static const PARAGRAPH_DOES_NOT_EXIST:String = "PARAGRAPH_DOES_NOT_EXIST";
		
		private var __paragraphs:Dictionary;
		private var __paragraphList:Array;
		
		public function get paragraphList():Array
		{
			return __paragraphList;
		}

		override protected function process(data:String):void
		{
			__paragraphList = [];
			__paragraphs = new Dictionary;
			
			var list:Array = data.split("\n");
			
			var reg:RegExp = new RegExp("[0-9]*");
			
			var lastParagraph:int = 0; 
			
			for (var i:int =0;i< list.length;i++)
			{
				var match:int = parseInt(list[i].match(reg));
				
				if (match)
				{
					__paragraphList.push(match);
					lastParagraph = match;
					__paragraphs[lastParagraph] = "";
				}
				else
				{
					__paragraphs[lastParagraph] += list[i];
				}
			}
			
			__paragraphList.sort(Array.NUMERIC);
		}
		
		
		public function getParagraphIndex(value:int):int
		{
			for (var i:int=0; i< __paragraphList.length;i++)	
				if (__paragraphList[i] == value)
					return i;
			
			return -1;
		}
		
		public function getParagraph(value:int):String
		{
			if(!__paragraphs[value])
				return PARAGRAPH_DOES_NOT_EXIST;
			
			return __paragraphs[value];
		}

		private function searchForError(data:String):void
		{
			//missing paragraphs starts at 183, 378, 1121, 1298, 1440, 1755, 1858
			var list:Array = data.split("\n");
			var d:Dictionary = new Dictionary;
			var reg:RegExp = new RegExp("[0-9]*");
			var lastParagraph:int = 0; 
			
			var s:int = 174;
			for (var i:int =0;i< list.length;i++)
			{
				var match:int = parseInt(list[i].match(reg));
				
				if (match)  
				{
					if (s+1 == match)
					{
						s++;
					}
					else
					{
						trace(match, i);
						return;
					}
				}
			}
		}
		
		override protected function get store():File
		{
			return super.store.resolvePath("book.txt");
		}
	}
}